package com.yy.finvideoplayer.utils

import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * @Description: BitmapSaveUtils
 * @Author: yiw89
 * @CreateDate: 2025/9/24 9:28
 * @Version: 1.0
 */
object BitmapSaveUtils {

    // 保存Bitmap到相册
    fun saveBitmapToGallery(
        context: Context,
        bitmap: Bitmap,
        onSuccess: (String) -> Unit,
        onError: (String) -> Unit
    ) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 使用 MediaStore
                saveBitmapToMediaStore(context, bitmap, onSuccess, onError)
            } else {
                // Android 9及以下使用传统方法
                saveBitmapToFile(context, bitmap, onSuccess, onError)
            }
        } catch (e: Exception) {
            onError("保存失败: ${e.message}")
        }
    }

    // Android 10+ 保存方法
    @Suppress("DEPRECATION")
    private fun saveBitmapToMediaStore(
        context: Context,
        bitmap: Bitmap,
        onSuccess: (String) -> Unit,
        onError: (String) -> Unit
    ) {
        try {
            val filename = "Screenshot_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(
                Date()
            )}.png"

            val contentValues = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, filename)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/VideoScreenshots")

                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
                    val filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath + "/VideoScreenshots"
                    put(MediaStore.Images.Media.DATA, "$filePath/$filename")
                }
            }

            val uri = context.contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
            )

            uri?.let {
                context.contentResolver.openOutputStream(it)?.use { outputStream ->
                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
                        onSuccess("图片已保存到相册")
                    } else {
                        onError("图片压缩失败")
                    }
                } ?: run {
                    onError("无法创建输出流")
                }
            } ?: run {
                onError("无法创建文件URI")
            }

        } catch (e: Exception) {
            onError("保存失败: ${e.message}")
        }
    }

    // Android 9及以下保存方法
    private fun saveBitmapToFile(
        context: Context,
        bitmap: Bitmap,
        onSuccess: (String) -> Unit,
        onError: (String) -> Unit
    ) {
        try {
            val picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val screenshotDir = File(picturesDir, "VideoScreenshots")

            if (!screenshotDir.exists()) {
                screenshotDir.mkdirs()
            }

            val filename = "Screenshot_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())}.png"
            val file = File(screenshotDir, filename)

            FileOutputStream(file).use { outputStream ->
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)) {
                    // 通知系统相册更新
                    context.sendBroadcast(
                        android.content.Intent(
                            android.hardware.Camera.ACTION_NEW_PICTURE,
                            android.net.Uri.fromFile(file)
                        )
                    )
                    onSuccess("图片已保存到: ${file.absolutePath}")
                } else {
                    onError("图片压缩失败")
                }
            }
        } catch (e: Exception) {
            onError("保存失败: ${e.message}")
        }
    }

    // 生成唯一的文件名
    private fun generateFileName(): String {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        return "VIDEO_SCREENSHOT_$timeStamp.png"
    }
}